package cn.swu.cs.lesson12

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.*
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlin.concurrent.thread

/**
 * Created by ghx on 2022/4/20.
 */
class DownloadService : Service() {

    val TAG = "@@DownloadService"

    lateinit var mBinder: DownloadBinder

    interface DownloadListener{
        fun onStart()
        fun onProgress(total:Int,current:Int)
        fun onFinished()
        fun onStop()
    }

    inner class DownloadBinder: Binder() {
        private var mListener:DownloadListener? = null
        private var stoped = false

        fun startDownload(listener:DownloadListener){
            Log.d(TAG,"startDownload")
            mListener = listener
            stoped = false
            thread {

                listener.onStart()

                val total = 10000
                var current = 0
                while(!stoped) {
                    current += 100
                    listener.onProgress(total, current)
                    Thread.sleep(500)

                    if(current >= total){
                        stoped = true
                        listener.onFinished()
                    }
                }
            }
        }

        fun stopDownload(){
            Log.d(TAG,"stopDownload")
            stoped = true
            mListener?.onStop()

        }

    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG,"onCreate")
        mBinder = DownloadBinder()

        val channelId = "my_service"
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val channel = NotificationChannel(channelId, "前台Service通知", NotificationManager.IMPORTANCE_DEFAULT)
                    manager.createNotificationChannel(channel)
                }
        val intent = Intent(this, MainActivity::class.java)
        val pi = PendingIntent.getActivity(this, 0, intent, 0)
        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setContentIntent(pi)
            .build()
        startForeground(1, notification)

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG,"onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        Log.d(TAG,"onDestroy")
        super.onDestroy()
    }


    override fun onBind(intent: Intent?): IBinder {
        Log.d(TAG,"onBind")
        return mBinder
    }
}